<?php
/**
 * Created by PhpStorm.
 * User: peiyu
 * Date: 2019/7/3
 * Time: 14:46
 */

namespace app\common\model;

use think\Model;
use Db;
use Log;

class dimension extends Model
{


    public static function saveDimension(array $data)
    {

        $keys = [];
        foreach ($data as $i => &$item) {
            $k = trim($item["key"]);
            if (!$k) continue;
            if (in_array($k, $keys)) {
                throw new \Exception("key 不能重复");
            } else {
                $keys[] = $k;
            }
            $item["key"] = $k;
            $item["title"] = trim($item["title"]);
            $item["sortby"] = $i;

            $values = array_get( $item,"values","");
            if(  array_get( $item,"if_free"   )!=1 && !$values)throw new \Exception($k.": 非自由模式值选项不能为空，必须是数组json格式");
            if($values){
                $_values = json_decode($values);
                if ($_values === NULL || !is_array($_values)) {
                    throw new \Exception($k.": 值选项格式不正确，必须是数组json格式");
                }
            }


            unset($item["id"]);
        }
        self::addColumn($data);

        self::where("id", ">", 0)->delete();
        foreach ($data as $i => &$item) {
            if (array_get($item, "key")) self::create($item);
        }
        $catch_key = config("my.catchKEY.dimension");
        cache($catch_key,null);

    }


    //获得维度 常用
    public static function getDimension()
    {
        $catch_key = config("my.catchKEY.dimension");
        $_v = cache($catch_key);
        if ($_v) return $_v;

        $list = self::getDimensionList();
        $ret = [];
        foreach ($list as $item) {
            $ret[$item["key"]] = $item["title"];
        }
        if ($ret) cache($catch_key, $ret, 3600);
        return $ret;
    }


    public static function getDimensionList()
    {

        $conf = self::order("sortby")->select()->toArray();
        foreach ($conf as &$item){
            $item["values_array"]=[];
            if($item["values"])$item["values_array"]= json_decode($item["values"],true) ;

        }
        return $conf;
    }


    private static function addColumn(array $arr)
    {
        $old = self::getDimension();
        $needadd = [];
        $dimension_black = dictionary::get_("dimension_black");

        $_key_title = [];
        foreach ($arr as &$item) {
            $key = trim($item["key"]);
            if (!$key) continue;
            if( in_array($key,$dimension_black) )throw new \Exception($key."已被使用，请换个名字！");
            if (!array_key_exists($key, $old)) {
                $needadd[] = $key;
                $_key_title[$key] = trim($item["title"]);
            }
        }
        if ($needadd) {
            $needaddcolumns = config::checkDimension($needadd);
            if ($needaddcolumns) {

                $sql = "";
                try {
                    foreach ($needaddcolumns as $column) {
                        $sql = "ALTER TABLE `config` ADD COLUMN `" . $column . "`  varchar(50) NOT NULL DEFAULT '' COMMENT '" . $_key_title[$column] . "' ;";
                        Db::execute($sql);
                    }

                } catch (\Exception $e) {
                    $msg = "执行sql失败，请手动添加列后再次执行此次操作，详情查看日志。" . $e->getMessage() . ":sql：" . $sql;
                    Log::error($msg);
                    throw new \Exception($msg);
                }
            }

        }

    }

}